package com.shenmazong.servereduuser.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.shenmazong.servereduuser.entity.TbUser;
import com.shenmazong.servereduuser.entity.TbUserRole;
import com.shenmazong.servereduuser.mapper.TbUserMapper;
import com.shenmazong.servereduuser.mapper.TbUserRoleMapper;
import com.shenmazong.servereduuser.service.TbUserRoleService;
import com.shenmazong.utils.ResultResponse;
import com.shenmazong.vo.BatchChooseIdVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 *
 */
@Service
public class TbUserRoleServiceImpl implements TbUserRoleService {

    @Autowired
    private TbUserRoleMapper tbUserRoleMapper;

    @Autowired
    private TbUserMapper userMapper;

    @Override
    public ResultResponse createRoleToUser(Long userId, ArrayList<Long> roleIds) {
        if(roleIds.size()<=0){
            return ResultResponse.FAILED(404,"请至少为此用户选择一个角色");
        }

        TbUser tbUser = userMapper.selectById(userId);
        if(tbUser==null){
            return ResultResponse.FAILED(500,"用户不存在");
        }

        for (Long roleId : roleIds) {
            TbUserRole tbUserRole=new TbUserRole();
            tbUserRole.setUserId(userId);
            tbUserRole.setRoleId(roleId);
            tbUserRoleMapper.insert(tbUserRole);
        }

        return ResultResponse.SUCCESS(200,"添加成功");
    }

    @Override
    public ResultResponse deleteRoleByUserRoleIds(BatchChooseIdVo chooseIdVo) {
        if(chooseIdVo.getIds().size()<=0){
            return ResultResponse.FAILED(404,"请至少选择一条用户的角色记录进行删除");
        }

        try {
            tbUserRoleMapper.deleteBatchIds(chooseIdVo.getIds());
        } catch (Exception e) {
            e.printStackTrace();
            return ResultResponse.FAILED(500,"删除用户的角色记录失败");
        }
        return ResultResponse.SUCCESS(200,"删除用户的角色记录成功");
    }

    @Override
    public ResultResponse getAllRoleByUserId(Long userId) {
        List<TbUserRole> tbUserRoles = tbUserRoleMapper.selectList(
                new QueryWrapper<TbUserRole>().lambda().eq(TbUserRole::getUserId, userId)
        );

        if(tbUserRoles.size()<=0){
            return ResultResponse.FAILED(404,"用户无任何角色信息");
        }

        return ResultResponse.SUCCESS(tbUserRoles);
    }

    @Override
    public ResultResponse updateRoleByUserId(TbUserRole userRole) {
        if(userRole.getUserRoleId()==null || userRole.getUserRoleId()==0){
            return ResultResponse.FAILED(404,"用户的角色记录id 为空 更新失败");
        }
        try {
            tbUserRoleMapper.updateById(userRole);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultResponse.FAILED(500,"用户的角色记录更新失败");
        }
        return ResultResponse.SUCCESS(200,"更新成功");
    }

}




